#include<bits/stdc++.h>
using namespace std;
const int N=1e3+5;
int t,mod,n,a[N][N],b[N][N],c[N][N],d[N][N],o;
int main()
{
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>t;
	while(t--)
	{
		cin>>mod>>n;
		o=0;
		for(int i=1;i<=n;++i)
			for(int j=1;j<=n;++j)
				cin>>a[i][j],d[i][j]=0;
		for(int i=1;i<=n;++i)
			for(int j=1;j<=n;++j)
				cin>>b[i][j];
		for(int i=1;i<=n;++i)
			for(int j=1;j<=n;++j)
				cin>>c[i][j];
		for(int i=1;i<=n;++i)
		{
			for(int j=1;j<=n;++j)
			{
				for(int z=1;z<=n;++z)
				{
					d[i][j]=(1ll*a[i][z]*b[z][j]%mod+d[i][j])%mod;
				}
				if(d[i][j]!=c[i][j])
				{
					o=1;
					break;
				}
			}
			if(o||i>300)
				break;
		}
		if(!o)
			cout<<"Yes"<<'\n';
		else
			cout<<"No"<<'\n';
	}
	return 0; 
}
